#!/usr/bin/python
# -*- coding: UTF-8 -*-

from lib.base import Douyin
import random, os, logging, sys
from PIL import Image

class Follow(Douyin):
    def __init__(self, sn):
        self.follow_num = 0
        super(Follow, self).__init__(sn)
        fd = open("{0}/../log/follow/{1}.log".format(os.path.dirname(__file__), sn), "w")
        sys.stdout = sys.stderr = fd

    def click_video(self):
        trys = 0
        while True:
            count = self.device(resourceId="com.ss.android.ugc.aweme:id/a9n").count
            if count > 0:
                break
            trys = trys + 1
            if trys > 10:
                raise RuntimeError("10S未进入城市页")
            self.sleep(1)
        
        random_num = int(random.uniform(0, count-1))
        logging.warning("随机点击{}".format(random_num))
        resp = self.device(resourceId="com.ss.android.ugc.aweme:id/a9n", instance=random_num).click_exists(timeout=10)
        self.reportClick(resp, "没有找到视频")
        #self.device(text="继续").click_exists(timeout=8)

    def get_in_video(self):
        self.click_video()
        if self.device(text="取消").click_exists(timeout=3):
            self.swipe_up()
            return self.get_in_video()

        """
        while self.device(text="说点什么...").exists(timeout=5):
            self.press_back()
            self.device(text="直接退出").click_exists(timeout=5)
            self.click_video()
        """

    def press_avatar(self):
        self.click_resource_and_check("com.ss.android.ugc.aweme:id/b52", "没找到头像")
        if self.device(text="取消").click_exists(timeout=3):
            self.press_back()
            self.sleep(1)
            self.swipe_up()
            return self.get_in_video()

    def is_woman(self):
        # 判断是否在用户主页
        sex_label = self.device(resourceId="com.ss.android.ugc.aweme:id/af3").exists(timeout=8)
        if not sex_label:
            return False

        """ 检查是否为女性 """
        path = self.screenshot()
        im = Image.open(path).convert("RGB")
        pixs = im.load()
        
        # 从 850 到 925 遍历查找颜色
        for p in range(850, 1230):
            pix = pixs[80, p]
            # print(pix)
            hex_color = RgbToHex(pix)

            # print(hex_color)
            if hex_color == "#d94965":
                return True

        return False

    def handle(self):
        while True:
            self.get_in_video()
            self.press_avatar()

            if self.is_woman():
                break
            self.press_back()
            self.press_back()
            self.swipe_up()
            self.swipe_up()

        funs_count = self.device(resourceId="com.ss.android.ugc.aweme:id/afg").get_text()
        if funs_count and funs_count.find('w')<0 and funs_count.find('k')<0 and int(funs_count) < 50:
            logging.warning("粉丝数太少换一个")
            self.press_back()
            self.press_back()
            return self.handle()

        self.click_resource_and_check("com.ss.android.ugc.aweme:id/afg", "没找到粉丝")

        if self.device(text="TA的粉丝").exists(timeout=10) == False:
            raise RuntimeError("进入粉丝页失败")

        while True:
            if self.device(text="@已重置").exists():
                self.swipe_up()
                continue
            
            if self.device(text="暂时没有更多了").exists():
                for i in range(3):
                    self.press_back()
                    self.sleep(1)

                for i in range(3):
                    self.swipe_up()
                self.sleep(1)
                return self.handle()

            if self.device(text="关注").click_exists() == True:
                self.follow_num += 1
                if self.follow_num > 25:
                    return self.follow_num
            else:
                self.swipe_up()
    
    def start(self, p_name):
        self.open_douyin_by_packname(p_name)
        if self.click_city() == False:
            raise RuntimeError("没点击城市")

        if self.device(resourceId="com.ss.android.ugc.aweme:id/a9n").exists(timeout=10) == False:
            raise RuntimeError("不在城市页")

        return self.handle()        


def RgbToHex(rgb):
    """ RGB 颜色值转为 16 进制 """
    return '#%02x%02x%02x' % rgb